<?php

namespace App\Services;

use App\Exceptions\InternalException;
use App\Models\Column;
use App\Models\ColumnCourse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ColumnService
{
    public function get($title,$type_id = 0)
    {
        $sql = Column::when($title, function ($query, $title) {
            return $query->where(function($query) use ($title) {
                $query->where('title','like', '%'.$title.'%');
            });
        });
        return $sql;
    }

    public function insert($input,$courses){
        try {
            $data = DB::transaction(function () use ($input,$courses) {
                $data = Column::create($input);
                $insert = [];
                foreach ($courses as $k => $v) {
                    $arr = [];
                    $arr['title'] = $v->title;
                    $arr['column_id'] = $data->id;
                    $arr['sort'] = $v->sort ?? 0;
                    $arr['cover'] = '';
                    $arr['course_id'] = $v->id;
                    $insert[] = $arr;
                }
                ColumnCourse::insert($insert);
                return $data;
            });

            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

    public function update($input,$courses){
        $id = $input['id'];
        unset($input['id']);
        try {
            $data = DB::transaction(function () use ($input,$courses,$id) {
                $data = Column::where('id',$id)->update($input);
                $insert = [];
                foreach ($courses as $k => $v) {
                    $arr = [];
                    $arr['title'] = $v->title;
                    $arr['column_id'] = $data->id;
                    $arr['sort'] = $v->sort ?? 0;
                    $arr['cover'] = '';
                    $arr['course_id'] = $v->id;
                    $insert[] = $arr;
                }
                ColumnCourse::where('column_id',$id)->delete();
                ColumnCourse::insert($insert);
                if($data){
                    return $id;
                }
            });

            return $data;
        } catch (\Throwable $th) {
            Log::info(json_encode($th));
            throw new InternalException('提交失败');
        }
    }

}